// member_token.go
package models_mongo

import (
	"time"
	"github.com/satori/go.uuid"
	"martini_template/componnet"
	"gopkg.in/mgo.v2/bson"
)

var tCollection = "member_token"

type MemberToken struct{
	AccessToken string `bson:"access_token"`
	CreateTime int64 `bson:"create_time"`
	ExpireTime int64 `bson:"expire_time"`
	DeviceCode string `bson:"device_code"`
	DeviceName string `bson:"device_name"`
	Ip string `bson:"ip"`
	MemberId string `bson:"member_id"`
}

var expire_time int64 = 3600

func (mt *MemberToken)CreateToken()bool{
	mt.AccessToken = componnet.Md5String(uuid.NewV4().String())
	mt.CreateTime = time.Now().Unix()
	mt.ExpireTime = mt.CreateTime + expire_time
	insertErr := mongoDb.C(tCollection).Insert(mt)
	if insertErr == nil{
		return true
	}else{
		componnet.Elogger.Println(insertErr)
		return false
	}
}

func (mt *MemberToken) Load(memberId string,devCode string)bool{
	loadErr := mongoDb.C(tCollection).Find(bson.M{"member_id":memberId,"device_code":devCode}).One(mt)
	if loadErr == nil{
		return true
	}else{
		componnet.Elogger.Println(loadErr)
		return false
	}
}

func (mt *MemberToken) CheckExpireToken(){
	currentTime := time.Now().Unix()
	mongoDb.C(tCollection).RemoveAll(bson.M{"expire_time":bson.M{"$lt":currentTime}})
}

func (mt *MemberToken) LoadByToken(token string) bool{
	loadErr := mongoDb.C(tCollection).Find(bson.M{"access_token":token}).One(mt)
	if loadErr != nil{
		componnet.Elogger.Println(loadErr)
		return false
	}else{
		return true
	}
}